﻿using PortfolioApp.Data;
using PortfolioApp.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PortfolioApp.Web.Models
{
    /// <summary>
    /// View Model for paging supported API calls to get posts.
    /// If CurrentPage is set out of range, will return the highest
    /// or lowest page possible.
    /// </summary>
    public class PostIndexVM
    {
        public List<Post> Posts { get; set; }
        public int CurrentPage { get; set; }
        public int PageSize { get; set; }

        /// <summary>
        /// Finds the posts from a DbContext for the specified page.
        /// </summary>
        /// <param name="db">The database context</param>
        public void LoadPostsForPage(ApplicationDbContext db)
        {
            int count = db.Posts.Count();

            // Sets the CurrentPage to the requested value or the
            // maximum/minimum value if the requested page is out of range.
            CurrentPage = Math.Max(0, Math.Min(CurrentPage, count / PageSize));

            int targetIndex = CurrentPage * PageSize;

            Posts = db.Posts.OrderBy(x => x.TimeStamp).Skip(targetIndex).Take(PageSize).ToList();
        }

        public PostIndexVM()
        {
            Posts = new List<Post>();
            CurrentPage = 0;
            PageSize = 5;
        }
        public PostIndexVM(int currentPage, int pageSize = 5)
        {
            Posts = new List<Post>();
            CurrentPage = currentPage;
            PageSize = pageSize;
        }
        public int PostCount()
        {
            return Posts.Count();
        }

    }
}